package gw.com.android.ui.account;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.GTDataResolve;
import gw.com.android.presenter.LoginPresenter;
import gw.com.android.presenter.PhoneLoginPresenter;
import gw.com.android.presenter.PresenterImpl;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.BindEnterPasswordDialog;
import gw.com.android.ui.dialog.PhoneLoginDialog;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.gesture_pwd.consts.GesturePwdConst;
import gw.com.android.ui.me.PhoneNumber;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringUtils;
import www.com.library.view.BtnClickListener;
import www.com.library.view.TintImageView;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity implements PresenterImpl {

    @BindView(R.id.loginnameEditText)
    EditText mLoginEditView;
    @BindView(R.id.login_drop_down)
    TintImageView mLoginDropView;
    @BindView(R.id.password)
    EditText mPassWordView;
    @BindView(R.id.login_remember_password)
    ImageView mSavePassView;
    @BindView(R.id.user_icon)
    ImageView userIcon;
    @BindView(R.id.username_histroy)
    RecyclerView histroyList;
    @BindView(R.id.username_content_clean)
    View usernameCleaner;
    @BindView(R.id.password_content_clean)
    View passwordCleaner;
    @BindView(R.id.username_hint)
    View usernameHint;
    @BindView(R.id.password_hint)
    View passwordHint;
    @BindView(R.id.sign_in_button)
    TextView loginBtn;
    @BindView(R.id.login_progress)
    ProgressBar loginProgress;

    private String mCurName = "";
    private String mPassword = "";
    private boolean isIconHide = false;
    /**
     * 登录账号列表数据
     */
    private ArrayList<String> mLoginList = null;

    private LoginPresenter mPresenter;
    private int mSeq = 0;
    private LoginHistroyAdapter histroyAdapter;
    private ValueAnimator anim;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initLayoutView() {
        AppTerminal.instance().setLoginView(1);
        GTConfig.instance().hasShowMain = false;
        mTitleBar.setAppTitle(AppMain.getAppString(R.string.login_title));
        mTitleBar.setRightIcon(R.mipmap.a_nav_service_b);
        mTitleBar.setBtnClickListener(new BtnClickListener() {
            @Override
            public void onBtnClick(int viewID) {
                if (viewID == R.id.title_left_icon) {
                    mPresenter.closeLogin(LoginActivity.this);
                } else if (viewID == R.id.title_right_icon) {
                    ConfigSettingDeal mDeal = new ConfigSettingDeal();
                    mDeal.openQQ(LoginActivity.this, ConfigType.QQ_SOURCE_LOGIN);
                }
            }
        });
        histroyList.setLayoutManager(new LinearLayoutManager(this));
        histroyAdapter = new LoginHistroyAdapter(this);
        histroyList.setAdapter(histroyAdapter);
        histroyAdapter.setOnItemListener(new LoginHistroyAdapter.OnItemListener() {
            @Override
            public void onItemClick(String item) {
                if (mLoginEditView != null && null != item) {
                    mLoginEditView.setText(item);
                    if (mLoginEditView.length() > 0) {
                        mLoginEditView.setSelection(item.length());
                    }
                }
                String loginPass = GTConfig.instance().getLoginPass(item);
                mPassWordView.setText(loginPass);
                if (loginPass != null && loginPass.length() > 0) {
                    mPassWordView.setSelection(loginPass.length());
                }
            }

            @Override
            public void onDeleteItem(String item) {
                if (mLoginList != null) {
                    mLoginList.remove(item);
                    GTConfig.instance().updateLoginList(item, histroyAdapter.getData());
                    if (item.equals(mLoginEditView.getText().toString())) {
                        mLoginEditView.setText("");
                        mPassWordView.setText("");
                    } else {
                        showHistroyList(mLoginList);
                    }
                    if (mLoginList.isEmpty()) {
                        onHistroyEmpty();
                    }
                }
            }
        });
        mPresenter = new LoginPresenter(LoginActivity.this);
    }

    @Override
    protected void initViewData() {
        mLoginEditView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String text = mLoginEditView.getText().toString();
                if (hasFocus) {
                    if (text.trim().length() > 0) {
                        associateLoginName(text);
                    }
                    showHint(usernameHint);
                    hideIcon();
                } else {
                    hideHint(usernameHint);
                    hideHistroyList();
                }
                showCleaner(mLoginEditView, usernameCleaner);
            }
        });
        mPassWordView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showHint(passwordHint);
                    hideIcon();
                } else {
                    hideHint(passwordHint);
                }
                showCleaner(mPassWordView, passwordCleaner);
            }
        });
        mLoginEditView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 如果输入的用户名在下拉框中,则带入相应密码到密码输入框中
                String input = mLoginEditView.getText().toString();
                associateLoginName(input);
                if (StringUtils.isHasStrInArray(input, mLoginList)) {
                    String loginPass = GTConfig.instance().getLoginPass(input);
                    mPassWordView.setText(loginPass);
                    if (loginPass != null && loginPass.length() > 0) {
                        mPassWordView.setSelection(loginPass.length());
                    }

                    //userIcon.setImageResource(R.mipmap.a_show_profiles);
                    // 匹配到历史登陆的账号后，查询该账号本地的头像并显示
//                    ProfileData profile = new ProfileRequest().fetchLocal(input);
//                    if (profile != null) {
//                        if (TextUtils.isEmpty(profile.avatar)) {
//                            userIcon.setImageResource(profile.isFemale() ? R.mipmap.a_profiles_f : R.mipmap.a_show_profiles);
//                        } else {
//                            Drawable drawable = userIcon.getDrawable();
//                            Glide.with(LoginActivity.this).load(profile.avatar).placeholder(drawable).error(drawable).transform(new GlideCircleTransform(getApplicationContext())).into(userIcon);
//                        }
//                    } else {
//                        userIcon.setImageResource(R.mipmap.a_show_profiles);
//                    }
                } else {
                    mPassWordView.setText("");
                }
                showCleaner(mLoginEditView, usernameCleaner);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mPassWordView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String username = mLoginEditView.getText().toString();
                String password = mPassWordView.getText().toString();
                if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
                    loginBtn.setEnabled(true);
                    loginBtn.setTextColor(getResources().getColor(R.color.color_f));
                } else {
                    loginBtn.setEnabled(false);
                    loginBtn.setTextColor(0xFFCFCFCF);
                }
                showCleaner(mPassWordView, passwordCleaner);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mPassWordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id,
                                          KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE) {
                    accLogin();
                    return true;
                }
                return false;
            }
        });
        changAccType(GTConfig.instance().getAccountType());
    }

    private void showCleaner(EditText et, View cleaner) {
        if (et != null && !TextUtils.isEmpty(et.getText()) && et.hasFocus()) {
            cleaner.setVisibility(View.VISIBLE);
        } else {
            cleaner.setVisibility(View.GONE);
        }
    }

    /**
     * 获取登录账号和密码相关信息
     */
    private void getLoginInfo() {
        mLoginList = GTConfig.instance().getLoginList();
        mCurName = GTConfig.instance().getLoginName();
        mPassword = GTConfig.instance().getLoginPass(mCurName);
        Logger.e(mLoginList.toString() + ", " + mCurName + ", " + mPassword);
        if ("".equals(mCurName) && null != mLoginList && mLoginList.size() > 0) {
            mCurName = mLoginList.get(mLoginList.size() - 1);
            mPassword = GTConfig.instance().getLoginPass(mCurName);
        }
        mLoginEditView.setText(mCurName);
        mPassWordView.setText(mPassword);
        mLoginEditView.setSelection(mCurName.length());
        if (null != mLoginList && mLoginList.size() > 0 && !"".equals(mLoginList.get(0))) {
            mLoginDropView.setVisibility(View.VISIBLE);
        } else {
            onHistroyEmpty();
        }
        boolean isRemember = GTConfig.instance().isRememberPassword();
        mSavePassView.setImageResource(isRemember ? R.mipmap.a_login_checked : R.mipmap.a_login_normal);
    }

    private void onHistroyEmpty() {
        mLoginDropView.setVisibility(View.GONE);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) usernameCleaner.getLayoutParams();
        if (params.rightMargin != 0) {
            params.rightMargin = 0;
            usernameCleaner.setLayoutParams(params);
        }
    }

    /**
     * 账号输入信息后联想功能
     */
    private void associateLoginName(String str) {
        if (!TextUtils.isEmpty(str) && null != mLoginList && mLoginList.size() > 0) {
            List<String> tempList = new ArrayList<>();
            for (int i = 0; i < mLoginList.size(); i++) {
                String item = mLoginList.get(i);
                if (item != null && !str.equals(item) && item.contains(str)) {
                    tempList.add(item);
                }
            }
            showHistroyList(tempList);
        } else {
            hideHistroyList();
        }
    }

    private void showHistroyList(List<String> list) {
        if (histroyAdapter == null) {
            return;
        }
        if (list == null || list.isEmpty()) {
            hideHistroyList();
            return;
        }
        ObjectAnimator rotation = ObjectAnimator.ofFloat(mLoginDropView, "rotation", 0, 180);
        rotation.setDuration(200);

        if (anim != null && anim.isRunning()) {
            anim.end();
        }
        histroyAdapter.replaceData(list);

        int count = list.size() > 3 ? 3 : list.size();
        int dHeight = count * DeviceUtil.instance().dip2px(40, this);

        ViewGroup.LayoutParams params = histroyList.getLayoutParams();
        final int mHeight = params.height;
        if (mHeight == dHeight) {
            histroyAdapter.notifyDataSetChanged();
            return;
        }

        anim = ValueAnimator.ofInt(mHeight, dHeight);
        anim.setDuration(200);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer value = (Integer) animation.getAnimatedValue();
                ViewGroup.LayoutParams params = histroyList.getLayoutParams();
                params.height = value;
                histroyList.setLayoutParams(params);
                histroyList.getAdapter().notifyDataSetChanged();
            }
        });
        anim.start();
        rotation.start();
    }

    private void hideHistroyList() {
        ObjectAnimator rotation = ObjectAnimator.ofFloat(mLoginDropView, "rotation", 180, 360);
        rotation.setDuration(200);

        if (anim != null && anim.isRunning()) {
            anim.end();
        }
        ViewGroup.LayoutParams params = histroyList.getLayoutParams();
        final int mHeight = params.height;
        if (mHeight <= 0) {
            return;
        }
        anim = ValueAnimator.ofInt(mHeight, 0);
        anim.setDuration(200);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer value = (Integer) animation.getAnimatedValue();
                ViewGroup.LayoutParams params = histroyList.getLayoutParams();
                params.height = value;
                histroyList.setLayoutParams(params);
                histroyList.getAdapter().notifyDataSetChanged();
            }
        });
        anim.start();
        rotation.start();
    }

    @Override
    public void onRequestSuc(Object result) {
        Logger.i("LoginActivity 登录回包接收到回调");
        //hideLoading();
        mPresenter.isLoading = false;
        onLoginSuccess(mCurName);
         ActivityManager.showMainTab(LoginActivity.this, ConfigType.TAB_HOME_TAG, AppContances.FROM_LOGIN_ACTIVITY);
        //在这里增加，如果是自动登录成功，则根据条件判定是否需要进入手势设置界面
        try {
            ActivityManager.dispatchGesture("dispatchGestureTag1:byUser", LoginActivity.this, GesturePwdConst.MODE_SETTING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LoginActivity.this.finish();
    }

    @Override
    public void onRequestFail(int failCode) {
        Logger.i("LoginActivity 登录回包接收到回调");
        hideLoading();
        String error;
        if (failCode >= 1100 && failCode < 1200) {
            error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1100) + "(" + failCode + ")";
        } else {
            error = ConfigUtil.instance().getErrorConfigObject().optString(failCode + "");
        }
        dealException(error);

        if (GTConfig.instance().getBooleanValue(GTConfig.PREF_AUTO_LOGIN)) {
            GTConfig.instance().setBooleanValue(GTConfig.PREF_AUTO_LOGIN, false);
        }
        mPresenter.isLoading = false;
        GTConfig.instance().isFromLogin = false;
    }

    @OnClick(R.id.login_forgot_password)
    void openForgotView() {
        DataItemDetail item = new DataItemDetail();
        item.setStringValue(ConfigType.CONFIG_TYPE_KEY_TAG, ConfigType.FORGET_PWD_TAG);
        item.setStringValue(ConfigType.CONFIG_TYPE_TYPE_TAG, ConfigType.CONFIG_TYPE_TYPE_URL_TAG);
        item.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, AppMain.getAppString(R.string.forget_title));

        ActivityManager.showWebPageActivity(LoginActivity.this, item, AppMain.getAppString(R.string.btn_back));
    }

    /**
     * 切换账号类型
     */
    private void changAccType(int accType) {
        //hideHistroyList();
        GTConfig.instance().setAccountType(accType);
        getLoginInfo();
    }

    @OnClick(R.id.login_drop_down)
    void dropDownFuc() {
        Logger.i("登录用户名下拉选中");
        if (anim != null && anim.isRunning()) {
            anim.end();
        }
        ViewGroup.LayoutParams params = histroyList.getLayoutParams();
        if (params.height > 0) {
            hideHistroyList();
        } else {
            showHistroyList(mLoginList);
        }
    }

    /**
     * 账号登录
     */
    @OnClick(R.id.sign_in_button)
    void accLogin() {
        if (!loginBtn.isEnabled()) {
            return;
        }
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        if (mPresenter.isLoading) {
            return;
        }
        mCurName = mLoginEditView.getText().toString().trim();
        mPassword = mPassWordView.getText().toString().trim();
        if (TextUtils.isEmpty(mCurName)) {
            dealException(AppMain.getAppString(R.string.login_account_null));
            return;
        } else if (TextUtils.isEmpty(mPassword)) {
            dealException(AppMain.getAppString(R.string.login_password_null));
            return;
        }
        showLoading();
        PhoneNumber.getInstance().reset();
        GTConfig.instance().isFromLogin = true;
        GTConfig.instance().isSubscribed = false;
        if (DeviceUtil.instance().isPhone(mCurName)) {//判断是否为手机号登录
            GTConfig.instance().mCurLoginPhone = mCurName;
            GTConfig.instance().isPhoneLogin = true;
            mSeq = GTSDataListener.curSeq++;
            PhoneLoginPresenter.instance().PhoneLoginFun(AppContances.NORMALREQ_TYPE_GET_CUSTOMERBYMOBILE, mSeq, mCurName, mPassword,
                    new PhoneLoginPresenter.OnMobileReqResultListener() {
                        @Override
                        public void reqResultSuccess(Object mObject) {
                            GTConfig.instance().setBooleanValue(GTConfig.PREF_AUTO_LOGIN, true);//登录成功了，那么就开启自动登录
                            JSONObject result = (JSONObject) mObject;
                            try {
                                if (!result.isNull("result")) {
                                    JSONObject resultObj = result.getJSONObject("result");
                                    if (!resultObj.isNull("customerNumber") && !resultObj.isNull("demoCustomerNumber")) {//1.绑定了真实和模拟账号，直接登录
                                        if (GTConfig.instance().getLastPhoneLoginType(mCurName) == GTConfig.ACC_TYPE_DEMO) {
                                            mCurName = resultObj.getString("demoCustomerNumber");
                                            Logger.i("用户点击账号登录按钮执行登录功能，demo登录");
                                            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);
                                            MobclickAgent.onProfileSignIn("Demo_Login", mCurName);
                                            MobclickEventUtlis.MobclickEvent(LoginActivity.this, "Demo_Login");
                                        } else {
                                            mCurName = resultObj.getString("customerNumber");
                                            Logger.i("用户点击账号登录按钮执行登录功能,real登录");
                                            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                                            MobclickAgent.onProfileSignIn("Real_Login", mCurName);
                                            MobclickEventUtlis.MobclickEvent(LoginActivity.this, "Real_Login");
                                        }
                                        execteLogin(mCurName, mPassword);
                                    } else {//2.只绑定了真实，但有关联的模拟账号（有一个，则关联绑定 有多个，则提示用账号登录）
                                        if (!resultObj.isNull("customerNumber") && resultObj.isNull("demoCustomerNumber")) {
                                            mCurName = resultObj.getString("customerNumber");
                                            DataItemResult itemResult = GTDataResolve.getInstance().dealPhoneLoginData(result, GTConfig.ACC_TYPE_DEMO);
                                            if (itemResult.getDataCount() == 1) {//登录页面，有绑定的账号，直接登录(如果有一个需要关联的账号，则关联后再登录)
                                                accSwitchAccount(mCurName, itemResult, GTConfig.ACC_TYPE_DEMO);
                                            } else if (itemResult.getDataCount() > 1) {
                                                hideLoading();
                                                dealException(AppMain.getAppString(R.string.title_to_accountlogin_tips));
//                                                execteLogin(mCurName,mPassword);
                                            } else {
                                                GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                                                execteLogin(mCurName, mPassword);
                                            }
                                        } else if (resultObj.isNull("customerNumber") && !resultObj.isNull("demoCustomerNumber")) {
                                            mCurName = resultObj.getString("demoCustomerNumber");
                                            DataItemResult itemResult = GTDataResolve.getInstance().dealPhoneLoginData(result, GTConfig.ACC_TYPE_REAL);
                                            if (itemResult.getDataCount() == 1) {//登录页面，有绑定的账号，没有关联账号，直接登录
                                                accSwitchAccount(mCurName, itemResult, GTConfig.ACC_TYPE_REAL);
                                            } else if (itemResult.getDataCount() > 1) {
                                                hideLoading();
                                                dealException(AppMain.getAppString(R.string.title_to_accountlogin_tips));
//                                                execteLogin(mCurName,mPassword);
                                            } else {
                                                GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);
                                                execteLogin(mCurName, mPassword);
                                            }
                                        } else {
                                            DataItemResult demoItemResult = GTDataResolve.getInstance().dealPhoneLoginData(result, GTConfig.ACC_TYPE_DEMO);

                                            DataItemResult realItemResult = GTDataResolve.getInstance().dealPhoneLoginData(result, GTConfig.ACC_TYPE_REAL);
                                            if (demoItemResult.getDataCount() > 1 || realItemResult.getDataCount() > 1) {
                                                hideLoading();
                                                dealException(AppMain.getAppString(R.string.title_to_accountlogin_tips));
                                            } else if (realItemResult.getDataCount() == 1) {
                                                accSwitchAccount("", realItemResult, GTConfig.ACC_TYPE_REAL);
                                            } else if (demoItemResult.getDataCount() == 1) {
                                                accSwitchAccount("", demoItemResult, GTConfig.ACC_TYPE_DEMO);
                                            }
                                        }
                                    }
                                } else {//result为null,且list>1
                                    DataItemResult demoItemResult = GTDataResolve.getInstance().dealPhoneLoginData(result, GTConfig.ACC_TYPE_DEMO);

                                    DataItemResult realItemResult = GTDataResolve.getInstance().dealPhoneLoginData(result, GTConfig.ACC_TYPE_REAL);
                                    if (demoItemResult.getDataCount() > 1 || realItemResult.getDataCount() > 1) {
                                        hideLoading();
                                        dealException(AppMain.getAppString(R.string.title_to_accountlogin_tips));
                                    }
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void reqResultFail(int failCode) {
                            GTConfig.instance().setBooleanValue(GTConfig.PREF_AUTO_LOGIN, false);//登录失败了，那么就取消自动登录
                            hideLoading();
                            String error;
                            if (failCode == 0 || failCode == 1012) {
                                MobclickEventUtlis.MobclickEvent(LoginActivity.this, "Phone_Login_error");
                                PhoneLoginDialog.showPhoneLoginDialog(LoginActivity.this, AppMain.getAppString(R.string.choose_to_phonelogin), new PhoneLoginDialog.onPhoneLoginListener() {

                                    @Override
                                    public void realPhoneLogin() {
                                        MobclickAgent.onProfileSignIn("Real_Login", mCurName);
                                        MobclickEventUtlis.MobclickEvent(LoginActivity.this, "Real_Login");
                                        exectePhoneLogin(mCurName, mPassword, GTConfig.ACC_TYPE_REAL);
                                    }

                                    @Override
                                    public void demoPhoneLogin() {
                                        MobclickAgent.onProfileSignIn("Demo_Login", mCurName);
                                        MobclickEventUtlis.MobclickEvent(LoginActivity.this, "Demo_Login");
                                        exectePhoneLogin(mCurName, mPassword, GTConfig.ACC_TYPE_DEMO);
                                    }
                                });
                            } else if (failCode == 7) {
                                error = AppMain.getAppString(R.string.account_locked);
                                dealException(error);
                            } else {
                                error = ConfigUtil.instance().getErrorConfigObject().optString(failCode + "");
                                dealException(error);
                            }
                        }
                    });
        } else {
            GTConfig.instance().mCurLoginPhone = "";
            GTConfig.instance().isPhoneLogin = false;
            if (mCurName.startsWith(ConfigUtil.instance().mConfigObject.optString(ConfigType.PREFIX_DEMO_ACCOUNT))) {
                Logger.i("用户点击账号登录按钮执行登录功能，demo登录");
                GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);
                MobclickAgent.onProfileSignIn("Demo_Login", mCurName);
                MobclickEventUtlis.MobclickEvent(this, "Demo_Login");
                execteLogin(mCurName, mPassword);
            } else {
                Logger.i("用户点击账号登录按钮执行登录功能,real登录");
                GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                MobclickAgent.onProfileSignIn("Real_Login", mCurName);
                MobclickEventUtlis.MobclickEvent(this, "Real_Login");
                execteLogin(mCurName, mPassword);
            }
        }


    }

    /**
     * 登陆成功后调用
     */
    private void onLoginSuccess(String username) {
        // loginList为空，或者不包含该用户名时，表示 该用户为第一次本地登陆。
        GTConfig.instance().setBooleanValue(username + GTConfig.PREF_LOCAL_FIRST_LOGIN, mLoginList == null || !mLoginList.contains(username));
        // 记录本地是否有真实账号登陆过
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL) {
            GTConfig.instance().setBooleanValue(GTConfig.PREF_REAL_ACCOUNT_LOGINED, true);
        }
    }

    private void accSwitchAccount(final String loginName, DataItemResult itemResult, final int accountType) {
        hideLoading();
        mPresenter.accSwitchAccount(loginName, itemResult, true, accountType, LoginActivity.this,
                new BindEnterPasswordDialog.BtnConfirmListener() {
                    @Override
                    public void onBtnClick(DataItemDetail item, String passWord) {
                        showLoading();
                        mSeq = GTSDataListener.curSeq++;
                        final String bindName = item.getString("customerNumber");
                        final String loginPassWord = passWord;
                        //绑定成功后 登录原来输入手机号已绑定的账号
                        PhoneLoginPresenter.instance().BindCustomerFun(AppContances.NORMALREQ_TYPE_BINDCUSTOMER, mSeq, accountType, bindName, loginPassWord,
                                new PhoneLoginPresenter.OnMobileReqResultListener() {
                                    @Override
                                    public void reqResultSuccess(Object mObject) {
                                        BindEnterPasswordDialog.instance().dismiss();
                                        if ("".equals(loginName)) {
                                            GTConfig.instance().setAccountType(accountType);
                                            //绑定成功后直接登录,绑定的是什么就登什么
                                            execteLogin(bindName, loginPassWord);
                                        } else {
                                            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                                            if (accountType == GTConfig.ACC_TYPE_DEMO) {
                                                //绑定成功后直接登录，绑定的模拟也登真实
                                                execteLogin(loginName, loginPassWord);
                                            } else {
                                                //绑定成功后直接登录,绑定的是真实也登真实
                                                execteLogin(bindName, loginPassWord);
                                            }
                                        }
                                    }

                                    @Override
                                    public void reqResultFail(int failCode) {
                                        hideLoading();
                                        if (failCode == 1) {
                                            BindEnterPasswordDialog.instance().setmErrorViewVisble(true);
                                        } else if (failCode == 7) {
                                            BindEnterPasswordDialog.instance().dismiss();
                                            String error = AppMain.getAppString(R.string.account_locked);
                                            dealException(error);
                                        } else {
                                            BindEnterPasswordDialog.instance().dismiss();
                                            String error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1100) + "(" + failCode + ")";
                                            dealException(error);
                                        }
                                    }
                                });
                    }
                });

    }

    @Override
    public void showLoading() {
        loginBtn.setText("");
        loginProgress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        loginBtn.setText(R.string.login_sign_in_register);
        loginProgress.setVisibility(View.GONE);
    }

    /**
     * 执行手机号直接登录逻辑
     */
    private void exectePhoneLogin(String loginPhoneNo, String loginPassWord, int accountType) {
        showLoading();
        mPresenter.mCurName = "";
        mPresenter.mCurLoginPhone = loginPhoneNo;
        mPresenter.mPassword = loginPassWord;
        GTConfig.instance().setAccountType(accountType);
        mPresenter.isLoading = true;
        mPresenter.isClickLogin = true;
        mPresenter.setPresenterImpl(this);
        DataManager.instance().reset();
        AppActivities.getSingleton().popAllActivityExceptOne(LoginActivity.this.getClass().getSimpleName());
        mPresenter.phoneLoginFun();
    }

    /**
     * 执行登录逻辑
     */
    private void execteLogin(String loginName, String loginPassWord) {
        mPresenter.mCurName = loginName;
        mPresenter.mPassword = loginPassWord;
        mPresenter.isLoading = true;
        mPresenter.isClickLogin = true;
        mPresenter.setPresenterImpl(this);
        DataManager.instance().reset();
        AppActivities.getSingleton().popAllActivityExceptOne(LoginActivity.this.getClass().getSimpleName());
        mPresenter.loginFun();
    }

    private void hideHint(View view) {
        view.clearAnimation();
        ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1.0F, 0F);
        alpha.setDuration(300);
        alpha.start();
    }

    private void showHint(View view) {
        view.clearAnimation();
        ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 0F, 1.0F);
        alpha.setDuration(300);
        alpha.start();
    }

    private void hideIcon() {
        if (isIconHide) {
            return;
        }
        isIconHide = true;
        ViewGroup.LayoutParams params = userIcon.getLayoutParams();
        final int iconWidth = params.width;
        final int iconHeight = params.height;
        ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
        anim.setDuration(300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float value = (Float) animation.getAnimatedValue();
                userIcon.setAlpha(value);
                ViewGroup.LayoutParams params = userIcon.getLayoutParams();
                params.width = (int) (iconWidth * value);
                params.height = (int) (iconHeight * value);
                userIcon.setLayoutParams(params);
            }
        });
        anim.start();
    }

    @OnClick(R.id.open_account_button)
    void openRealUrl() {
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        PackStatis.getToService(PackStatis.EventAction.CLICKNACCOUNT.getValue(), PackStatis.EventCategory.LOGIN.getValue(), null, null);
        MobclickEventUtlis.MobclickEvent(this, "Real_LoginView_Account");
        ActivityManager.showOpenAccount(LoginActivity.this, ConfigType.ADD_LOGIN_REAL_TAG);
        onBackPressed();
    }

    @OnClick(R.id.login_remember_password_container)
    void rememberPassword() {
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        boolean isRemember = !GTConfig.instance().isRememberPassword();
        mSavePassView.setImageResource(isRemember ? R.mipmap.a_login_checked : R.mipmap.a_login_normal);
        GTConfig.instance().savePasswordFlag(isRemember);
    }

    boolean hide = true;

    @OnClick(R.id.password_eye)
    void hidePassword(ImageView view) {
        hide = !hide;
        if (hide) {
            view.setImageResource(R.mipmap.a_me_eye_monvisible);
            mPassWordView.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            view.setImageResource(R.mipmap.a_me_eye_moninvisible);
            mPassWordView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
        mPassWordView.setSelection(mPassWordView.length());
    }

    @OnClick(R.id.username_content_clean)
    void cleanUsername() {
        mLoginEditView.setText("");
    }

    @OnClick(R.id.password_content_clean)
    void cleanPassword() {
        mPassWordView.setText("");
    }

    /**
     * 处理异常连接失败(比如登录超时、行情连接失败、交易连接失败等)
     *
     * @param errorShowMsg 提示的错误信息
     */
    private void dealException(String errorShowMsg) {
        PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(this, "", errorShowMsg);
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 重新该类，什么都不做，登陆界面不显示福利小弹窗的广告哟~~
     */
    @Override
    public void showNoviceWelfare(String title, String link) {
    }

    @Override
    public void finish() {
        super.finish();
        AppTerminal.instance().setLoginView(0);
        if (null != mPresenter) {
            mPresenter.setPresenterImpl(null);
            mPresenter.clear();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppTerminal.instance().setLoginView(0);
    }

    @Override
    public void onBackPressed() {
        mPresenter.closeLogin(LoginActivity.this);
    }

}
